package com.weayer.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.weayer.constant.TokenConstants;
import com.weayer.dto.TokenResult;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 自定义JWT类
 * @author: Weayer
 **/
public class JwtUtils {
    private static final String SIGN = "weayer@0102";
    private static final String JWT_KEY_PHONE = "passengerPhone";
    private static final String JWT_KEY_IDENTITY = "identity";  // 标识司机和乘客
    private static final String JWT_TOKEN_TYPE = "tokenType";   // 标识token类型
    private static final String JWT_TOKEN_TIME = "tokenTime";   // 生成时间
    // 生成token
    public static String generatorToken(String passengerPhone, String identity, String tokenType){
        Map<String, String> map = new HashMap<>();
        map.put(JWT_KEY_PHONE, passengerPhone);
        map.put(JWT_KEY_IDENTITY, identity);
        map.put(JWT_TOKEN_TYPE, tokenType);
        map.put(JWT_TOKEN_TIME, Calendar.getInstance().getTime().toString());

        JWTCreator.Builder builder = JWT.create();
        map.forEach(    // 整合map
                (k,v) -> {
                    builder.withClaim(k,v);
                }
        );
//        builder.withExpiresAt(date);   // 整合过期时间
        String sign = builder.sign(Algorithm.HMAC256(SIGN));
        return sign;
    }
    // 解析token
    public static TokenResult parseToken(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        String identity = verify.getClaim(JWT_KEY_IDENTITY).asString();
        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        return tokenResult;
    }
    // token 校验
    public static TokenResult checkToken(String token){
        TokenResult tokenResult = null;
        try{
            tokenResult = JwtUtils.parseToken(token);
        }catch (Exception e){

        }
        return tokenResult;
    }
    public static void main(String[] args) {

        System.out.println(generatorToken("110", "1", TokenConstants.ACCESS_TOKEN_TYPE));
        System.out.println(parseToken(generatorToken("110", "0", TokenConstants.REFRESH_TOKEN_TYPE)));

        System.out.println(generatorToken("18178101660", "1", TokenConstants.REFRESH_TOKEN_TYPE));
        System.out.println(parseToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzZW5nZXJQaG9uZSI6IjE4MTc4MTAxNjYwIiwiaWRlbnRpdHkiOiIxIiwidG9rZW5UaW1lIjoiTW9uIEphbiAxNSAyMDoxMzowOSBDU1QgMjAyNCIsInRva2VuVHlwZSI6InJlZnJlc2hUb2tlbiJ9.PtA9HHZ1tg8gdjxlJvzBptxja3ChAzSb0OT_4sPCJOI"));
    }
}
